import axios from 'axios'
const qs = require('qs')
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

//白名单接口，名单里的接口数据 不会被qs.stringify 处理
const whiteList = [
        '/agent/list',
        '/agent/get',
        '/agent/create',
        '/agent/update',
        '/system/role/menu/add', // 权限管理新增接口
        '/role/menu/update',
        '/system/role/agent/menu/update',
        '/system/user/add', // 新增账号接口
        '/system/organ/add',
        '/system/organ/update',
        '/system/user/update', // 编辑账号接口
        '/user/list', //账号管理列表接口
        '/user/uploadfile',// 账号管理批量导入接口
        '/system/menu/add',// 菜单新增
        "/role/menu/add",
        "meeting/video/list",    // 视频管理列表接口
        "meeting/video/getMeetingRecordList",
        '/meeting/file/saveMeetingFile',
        '/videoPool/uploadfile',
        '/meeting/videoFaceBusiness/picturelist',//视频获取截图
        '/meeting/videoFaceBusiness/query',//申请编号和视频业务数据查询
        '/ent/config/update'//增加和修改配置项
    ]
let baseURL = process.env.VUE_APP_BASE_API;
if(process.env.NODE_ENV === 'development'){
    baseURL=process.env.VUE_APP_BASE_API;
}else if(process.env.NODE_ENV === 'staging'){
    baseURL=window.vpm_test_config.BASE_URL;
}else {
    baseURL=window.vpm_config.BASE_URL;
}
    // create an axios instance
const service = axios.create({
    baseURL,
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 60000 // request timeout
})

let isAuth = true;
// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        const reqesturl = config.url;
        if (reqesturl == '/login' || reqesturl == '/logout') {
            config.data = qs.stringify(config.data)
            console.log("1",config);
            return config
        }
        if (getToken()) {
            config.headers['Authorization'] =  getToken()
        } else {
            if (isAuth) {
                MessageBox.alert('登录信息已失效，请先登录', '警告', {
                    confirmButtonText: '确定',
                })
            }
            isAuth = false;
            return;
        }
        if (whiteList.indexOf(reqesturl) != -1) {
            return config
        }
        config.data = qs.stringify(config.data)
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data
        if (res.size) {
            return response
        }
        if (!res) {
            Message({
                message: res.msg || 'Error2',
                type: 'error',
                duration: 5 * 1000
            })
            if (isAuth) {
                MessageBox.confirm('登录超时或认证失败，请重新登录', '重新登录', {
                    showClose: false,
                    distinguishCancelAndClose: true,
                    showCancelButton: false,
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                    confirmButtonText: '重新登录',
                    type: 'warning'
                })
            }
            isAuth = false;
            store.dispatch('user/resetToken').then(() => {
                location.reload()
            })
        }
        if (res.code !== 0 && response.status !== 200) {
            if (res.code === -401) {
                if (isAuth) {
                    MessageBox.confirm('登录超时或认证失败，请重新登录', '重新登录', {
                        showClose: false,
                        distinguishCancelAndClose: true,
                        showCancelButton: false,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        confirmButtonText: '重新登录',
                        type: 'warning'
                    })
                }
                isAuth = false;
                store.dispatch('user/resetToken').then(() => {
                    location.reload()
                })
            } else {
                Message({
                    message: "服务异常，请联系青牛工程师处理" || 'Error2',
                    type: 'error',
                    duration: 5 * 1000
                })
            }
            return Promise.reject(new Error(res.message || 'Error1'))
        } else {
            return res
        }
    },
    error => {
        console.log(error, 'afsafafa')
        const err = error + ''
            // 返回异常拦截
        if (err.indexOf('404') != -1) {
            if (isAuth) {
                Message({
                    message: '呀，找不到接口了' || 'Error2',
                    type: 'error',
                    duration: 3 * 1000
                })
            }
            isAuth = false;

        }
        if (err.indexOf('500') != -1 || err.indexOf('503') != -1) {
            if (isAuth) {
                MessageBox.confirm('服务端异常，请联系技术人员', '提示', {
                    showClose: false,
                    distinguishCancelAndClose: true,
                    showCancelButton: false,
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                    confirmButtonText: '确定',
                    type: 'warning'
                })
            }
            isAuth = false

        }
        if (err.indexOf('401') != -1) { //认证超时
            if (isAuth) {
                MessageBox.confirm('登录超时或认证失败，请重新登录', '重新登录', {
                    showClose: false,
                    distinguishCancelAndClose: true,
                    showCancelButton: false,
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                    confirmButtonText: '重新登录',
                    type: 'warning'
                })
            }
            isAuth = false;
            store.dispatch('user/resetToken').then(() => {
                location.reload()
            })
        }
        // Message({
        //   message: error.message,
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        // store.dispatch('user/resetToken').then(() => {
        //   location.reload()
        // })

        return Promise.reject("服务异常，请联系青牛工程师处理")
    }
)

export default service
